package com.cswnode.Controller;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Entity.Event;
import com.cswnode.Entity.User;
import com.cswnode.Event.EventProducer;
import com.cswnode.Service.LikeService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.Constant;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author csw
 * @create 2020/10/2 19:48
 */
@Controller
public class LikeController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;

    @ResponseBody
    @LoginJudgment
    @PostMapping("/like")
    public String like(int entityType,int entityId,int entityUserId,int postId){
        User user = hostHolder.getUser();
        //点赞
        likeService.like(user.getId(),entityType,entityId,entityUserId);
        //获取数量
        long entityLikeCount = likeService.findEntityLikeCount(entityType, entityId);
        //获取点赞状态
        int entityLikeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        //返回前端数据
        Map<String,Object> map = new HashMap<>();
        //返回数量
        map.put("entityLikeCount",entityLikeCount);
        //返回状态
        map.put("entityLikeStatus",entityLikeStatus);
        //触发点赞事件
        if (entityLikeStatus == Constant.USER_LIKE){
            Event event = new Event()
                    .setTopic(Constant.TOPIC_LIKE)
                    .setUserId(user.getId())
                    .setEntityId(entityId)
                    .setEntityType(entityType)
                    .setEntityUserId(entityUserId)
                    .setData("postId",postId);
            eventProducer.fireEvent(event);
        }


        return CommunityUtil.getJsonString(0,null,map);
    }

}
